package com.chengqs.rainbow.im.route.server.command;

import com.chengqs.rainbow.common.core.constant.RedisConstants;
import com.chengqs.rainbow.common.core.constant.SymbolConstants;
import com.chengqs.rainbow.common.im.constant.CommandType;
import com.chengqs.rainbow.common.im.constant.Constants;
import com.chengqs.rainbow.common.protobuf.Command;
import com.chengqs.rainbow.im.route.domain.Session;
import io.netty.channel.ChannelHandlerContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

/**
 * <B>主类名称：</B>OfflineServerCommandHandler<BR>
 * <B>概要说明：</B>enter<BR>
 *
 * @author: chengqs
 * @create: 2025-09-13 20:31:08
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class OfflineServerCommandHandler implements ServerCommandHandler {

    private final RedisTemplate<String, Session> redisTemplate;

    private final Executor taskExecutor;

    @Override
    public void handleCommand(Command command, ChannelHandlerContext ctx) {
        taskExecutor.execute(() -> {
            try {
                // 下线后删除session，一般是通过用户名移除其设备（如手机、平板等）
                redisTemplate.boundHashOps(
                        Constants.REDIS_SESSION_KEY + RedisConstants.KEY_SEPARATOR + command.getUserId()
                ).delete(String.valueOf(command.getClient()));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });
    }

    @Override
    public int getType() {
        return CommandType.COMMAND_OFFLINE;
    }
}
